
from os import stat
import cv2
import pyzbar.pyzbar as pyzbar
import RPi.GPIO as GPIO
from libs.ioctrl import IoCtrl

'''
二维码扫码相关功能组织到这里
'''
class Qrcode:
    '''
    解码并实时显示， 已取实时显示，因为要开UI线程？
    '''
    @staticmethod
    def decodeDisplay(image):
        barcodes = pyzbar.decode(image)
        datalist = []
        for barcode in barcodes:
            # 提取条形码的边界框的位置
            # 画出图像中条形码的边界框
            (x, y, w, h) = barcode.rect
            #cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
    
            # 条形码数据为字节对象，所以如果我们想在输出图像上
            # 画出来，就需要先将它转换成字符串
            barcodeData = barcode.data.decode("utf-8")
            barcodeType = barcode.type
            datalist.append(barcodeData)
            # 绘出图像上条形码的数据和条形码类型
            text = "{} ({})".format(barcodeData, barcodeType)
            #cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
            #            .5, (0, 0, 125), 2)
    
            # 向终端打印条形码数据和条形码类型
            print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData))
        return image, datalist
    '''
    循环读取帧
    '''
    @staticmethod
    def detect():
        
        IoCtrl.lightOpen()

        camera = cv2.VideoCapture(0)
    
        timeOut = 0
        brs = None
        while True:
            # 读取当前帧
            ret, frame = camera.read()
            # 转为灰度图像
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            im, brs = Qrcode.decodeDisplay(gray)
            cv2.waitKey(1)
            #如果检测到二维码结束检测，后续完善超时也结束检测
            if ( len(brs) >= 1 ):
                break
            
            # 超时 停止等待 扫描二维码
            timeOut=timeOut+1
            if(timeOut > 2000):
                break

        camera.release()

        IoCtrl.lightClose()

        return brs